package com.bw.base.mvvm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bw.net.Res
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel() {
    val onFailed by lazy { MutableLiveData<Throwable>() }
    fun <T>executeNewword(
        s:suspend ()-> Res<T>,
        success: (T) ->Unit,
        failed:(Throwable)->Unit = onFailed::postValue,
        okCode:Int = 0
    ){
        viewModelScope.launch {
            try {
                val res = s.invoke()
                if (res.code == okCode){
                    success(res.data)
                }else{
                    failed(RuntimeException(res.msg))
                }
            }catch (e:Exception){
                failed(e)
            }
        }
    }
}